/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.cursojava.server.bd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Zacarias
 */
public class ConexaoPostgres {
    public static Connection connection = null;
    public static Statement statement = null;
    public static ResultSet resultSet = null;
    public static final String DRIVER = "org.postgresql.Driver";

    public static boolean getConnection() {

        try {
            Class.forName(DRIVER);
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "123456");
            statement = (Statement) connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //statement permite navegaÃ§Ã£o pelos registros da tabela
            System.out.println("Conectou");
            return true;

        } catch (ClassNotFoundException erro) {
            erro.printStackTrace();
            return false;
        } catch (SQLException erro) {
            erro.printStackTrace();
            return false;
        }
    }

    /**
     * Fecha Resultset, Statement e connection
     */
    public static void close() throws Exception {// close encerra todos objetos que estavam sendo usados

        closeResultSet();
        try {
            closeStatement();
            closeConnection();
        } catch (Exception ex) {
           throw ex;
        }
        

    }

    private static void closeResultSet() {
        try {
            resultSet.close();
        } catch (SQLException erro) {
            erro.printStackTrace();
        }

    }

    private static void closeConnection() throws Exception {
        try {
            connection.close();
            System.out.println("Desconectou");
        } catch (Exception erro) {
            throw erro;
        }
    }

    private static void closeStatement() throws Exception {
        try {
            statement.close();
        } catch (Exception e) {
            throw e;
        }
    }

    public static void setResultSet(String sql) throws Exception {

        try {
            resultSet = statement.executeQuery(sql);
        } catch (Exception erro) {
            throw erro;
        }
    }

    public static int runSQL (String sql){

        int quant = 0;
        try
        {
            quant = statement.executeUpdate(sql);
        }
        catch (SQLException erro)
        {
            erro.printStackTrace();
        }
        return quant;
    }
    
    public Connection getConection(){
        return connection;
    }

}
